#include "Texture2D.h"
#include <glad/glad.h>
//#include "Image.h"
#include "Context.h"
#include "Graphics.h"
#include "Shader.h"

Texture2D::Texture2D(Context* context) :
	Texture(context)
{
	target_ = GL_TEXTURE_2D;
}

Texture2D::~Texture2D()
{
	Release();
}

bool Texture2D::BeginLoad(File& source)
{
	/*loadImage_ = new Image(context_);
	if (!loadImage_ || !loadImage_->Load(source))
	{
		delete loadImage_;
		return false;
	}*/

	return true;
}

bool Texture2D::EndLoad()
{
	//if (loadImage_) {
	//	//SetData(loadImage_);
	//	//delete loadImage_;
	//	loadImage_ = nullptr;
	//}

	return true;
}

void Texture2D::Release()
{
	if (textureID_)
	{
		glDeleteTextures(1, &textureID_);
		textureID_ = 0;
	}
}

bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
{
	if (width <= 0 || height <= 0)
	{
		return false;
	}
	width_ = width;
	height_ = height;
	format_ = format;
	usage_ = usage;
	return Create();
}

//bool Texture2D::SetData(Image* image)
//{
//	unsigned char* levelData = image->GetData();
//	int levelWidth = image->GetWidth();
//	int levelHeight = image->GetHeight();
//	unsigned format = image->GetFormat();
//	SetSize(levelWidth, levelHeight, format);
//	SetData(0, 0, levelWidth, levelHeight, levelData);
//	return true;
//}

bool Texture2D::SetData(int x, int y, int width, int height, const void* data)
{
	/*if (!textureID_)
	{
		assert(0);
		return false;
	}

	if (!data)
	{
		data = 0;
	}

	int levelWidth = width_;
	int levelHeight = height_;
	if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
	{
		assert("Illegal dimensions for setting data");
		return false;
	}

	context_->GetGraphics()->SetTextureForUpdate(this);
	UpdateParameters();
	bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight;
	unsigned format = format_;
	unsigned level = 0;
	if (wholeLevel)
		glTexImage2D(target_, level, format, width, height, 0, GetExternalFormat(format_), GetDataType(format_), data);
	else
		glTexSubImage2D(target_, level, x, y, width, height, GetExternalFormat(format_), GetDataType(format_), data);


	context_->GetGraphics()->SetTexture(0, nullptr);*/
	return true;
}

bool Texture2D::ReSize(int width, int height, unsigned format)
{
	if (!textureID_)
	{
		SetSize(width, height, format);
		SetData(0, 0, width, height, nullptr);
		return true;
	}

	//if (width_ != width || height_ != height)
	//{
	//	width_ = width;
	//	height_ = height;
	//	context_->GetGraphics()->SetTextureForUpdate(this);
	//	glTexImage2D(target_, 0, format_, width, height, 0, GetExternalFormat(format_), GetDataType(format_), 0);
	//	context_->GetGraphics()->SetTexture(0, nullptr);
	//	glCheckError();
	//	return true;
	//}
	return false;
	glCheckError();
}

bool Texture2D::Create()
{
	Release();
	glGenTextures(1, &textureID_);
	return true;
}


